package com.greenline.push.service.core.recv;

import java.util.Date;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.greenline.push.core.pushcenter.MsgForSendManager;
import com.greenline.push.dal.pushcenter.dataobject.MsgForSendDO;
import com.greenline.push.service.core.item.Packet;
import com.greenline.push.service.core.utils.Constants;
import com.greenline.push.service.core.utils.PacketConvertor;

public class DbReceiver implements IReceiver {

    @Autowired
    private MsgForSendManager msgForSendManager;

    @Autowired
    PacketConvertor convertor;
    private Logger log = Constants.LOG_PROCESS;

    @Override
    public boolean receive(Packet packet) {
        log.debug(String.format("dbreciver收到消息:domainId:%s,templateId:%s.param:%s", packet.getDomainId(), packet.getTemplateId(),
                packet.getParam()));

        MsgForSendDO msgForSendDO = convertor.convertPacketToForSendDO(packet);
        // 默认是成功
        Long sendingTime=packet.getSendingTime();
        Date d=(null==sendingTime)?null:new Date(sendingTime);
        msgForSendDO.setFetchCount(1);
        msgForSendDO.setClassId(packet.getClassId());
        msgForSendDO.setSendTime(d);
        Long id = null;
        try {
            // first insert into DB
            id = msgForSendManager.insert(msgForSendDO);
            // 插入成功后将id赋值给packet的DbMsgId
            packet.setDbMsgId(id);
        } catch (Exception e) {
            // throw Exception
            e.printStackTrace();
            log.error(String.format("{receive}异常:%s", e.getMessage()));
        }
        if (id != null) {
            return true;
        }
        return false;
    }

}
